package com.stgy.lease.web.admin.controller.attr;

import com.stgy.lease.common.redis.RedisPrefixEnum;
import com.stgy.lease.common.result.Result;
import com.stgy.lease.model.domain.PaymentType;
import com.stgy.lease.web.admin.service.PaymentTypeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * ClassName:PaymentTypeController
 * Package:com.stgy.lease.web.admin.controller
 * Description:
 *
 * @Author:helei
 * @Create:2024/8/28 - 11:29
 */
@Tag(name = "支付方式管理")
@RestController
@RequestMapping("/admin/payment")
public class PaymentTypeController {

    @Autowired
    private PaymentTypeService paymentTypeService;

    @Autowired
    private RedisTemplate redisTemplate;

    private String paymentListKey = RedisPrefixEnum.STGY_ADMIN_PREFIX + "payment:list";

    /**
     * http://localhost:5174/admin/payment/list GET
     *
     * @return
     */
    @Operation(summary = "查询所有支付方式")
    @GetMapping("/list")
    public Result<List<PaymentType>> list() {
        List<PaymentType> list = (List<PaymentType>) redisTemplate.opsForValue().get(paymentListKey);
        if (list == null) {
            list = paymentTypeService.list();
            redisTemplate.opsForValue().set(paymentListKey, list, 1, TimeUnit.DAYS);
        }
        return Result.ok(list);
    }

    /**
     * localhost:5174/admin/payment/saveOrUpdate POST
     * {id: "", name: "两年付", payMonthCount: 24, additionalInfo: "押一付二十四"}
     * 新增或者更新时，不能重复
     *
     * @param paymentType
     * @return
     */
    @Operation(summary = "新增或者更新支付方式")
    @PostMapping("/saveOrUpdate")
    public Result saveOrUpdate(@RequestBody PaymentType paymentType) {
        //唯一校验
        //新增时:name值已存在，不能新增
        //更新时：使用name查询数据，如果他的id值=要更新的记录的，表示名称没有修改，可以更新
        //如果查询到的记录id值！=要更新的记录，表示名称修改了和数据库中某条记录重复了 不能更新
        boolean b = paymentTypeService.saveOrUpdatePaymentType(paymentType);
        if (b) {
            redisTemplate.delete(paymentListKey);
        }
        return Result.build(b);
    }

    //http://localhost:5174/admin/payment/deleteById?id=1828684273117356034 DELETE
    @Operation(summary = "根据id删除支付方式")
    @DeleteMapping("/deleteById")
    public Result deleteById(@RequestParam("id") List<Long> ids) {
        boolean b = paymentTypeService.removeByIds(ids);
        if (b) {
            redisTemplate.delete(paymentListKey);
        }
        return Result.build(b);
    }

}